package com.hlkj.action.login;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.easy.tool.form.FormRead;
import com.easy.tool.results.ResultParameters;
import com.hlkj.tool.results.JsonBulid;
import com.hlkj.util.SQLFactory;
import com.hlkj.util.StringUtil;
import com.hlkj.webservice.SendMessage;

public class RegisterAction {

	/**
	 * 注册获取验证码
	 * 
	 */
	public String getValidateCode() {
		// http://127.0.0.1:8080/struts2_jdbc_5_30/register/getValidateCode?phone_number=18994874626
		FormRead form = new FormRead();
		String phone_number = form.getParamValue("phone_number");
		String code = StringUtil.getRandomNumber(6);
		JsonBulid jsonBulid = null;
		try {
			String sql = "SELECT 1 FROM yzm WHERE phone_number=?";
			int count = SQLFactory.queryCount(sql, phone_number);
			boolean result = SendMessage.setMessageValidateCode(phone_number,
					"验证码:" + code);
			if (count == 0) {// 未注册用户
				if (result) {// 验证码短信发送成功
					sql = "INSERT INTO yzm(phone_number,validate_number) VALUES(?,?)";
					count = SQLFactory.update(sql, phone_number, code);
					if (count == -1)
						jsonBulid = JsonBulid.success(false).msg("操作数据库失败!");
					else
						jsonBulid = JsonBulid.success(true).msg("操作数据库成功!");

				} else {
					jsonBulid = JsonBulid.success(false).msg("短信验证码发送失败!");
				}
			} else {// 已注册用户
				if (result) {// 验证码短信发送成功
					sql = "UPDATE yzm set validate_number=? WHERE phone_number=?";
					count = SQLFactory.update(sql, code, phone_number);
					if (count == -1)
						jsonBulid = JsonBulid.success(false).msg("操作数据库失败!");
					else
						jsonBulid = JsonBulid.success(true).msg("操作数据库成功!");

				} else {
					jsonBulid = JsonBulid.success(false).msg("短信验证码发送失败!");
				}
			}

		} catch (Exception e) {
			jsonBulid = JsonBulid.success(false).msg("操作异常!");
			e.printStackTrace();
		}

		ResultParameters.setJson(jsonBulid.json());
		return ResultParameters.JSON;
	}

	/**
	 * 注册jsp页面:/WebRoot/regist/regist.jsp
	 */
	public String regist() {
		// http://127.0.0.1:8080/struts2_jdbc_5_30/register/regist
		Map<String, Object> map =new HashMap<String, Object>();
		map.put("telPhone", "87666766");
		map.put("emil", "zhukui66@sina.com");
		map.put("addr", "南京玄武区");
		HttpServletRequest request = ServletActionContext.getRequest();
		request.setAttribute("testMap", map);
		
		return "regist";
	}

	public String doEdit() {
		FormRead form = new FormRead();
		String telPhone = form.getParamValue("telPhone");
		String emil = form.getParamValue("emil");
		String addr = form.getParamValue("addr");

		System.out.println(telPhone + "==" + emil + "==" + addr);

		ResultParameters.setJson(JsonBulid.success(true).msg("操作成功!").add("result", "success").json());
		return ResultParameters.JSON;
	}
}
